package com.groupbuying.store.service.impl;

import com.groupbuying.store.connector.SysconfigFeign;
import com.groupbuying.store.constants.CommonConstants;
import com.groupbuying.store.constants.StoreVirtualOperConstants;
import com.groupbuying.store.context.FilterContextHandler;
import com.groupbuying.store.controller.forManage.StoreVirtualAccountManageController;
import com.groupbuying.store.dao.StoreCapitalVirtualAccountDetailDao;
import com.groupbuying.store.domain.StoreCapitalVirtualAccountDO;
import com.groupbuying.store.domain.StoreCapitalVirtualAccountDetailDO;
import com.groupbuying.store.domain.StoreMainInfoDO;
import com.groupbuying.store.dto.forManage.StoreCapitalVirtualAccountDetailDto;
import com.groupbuying.store.service.StoreCapitalVirtualAccountDetailService;
import com.groupbuying.store.service.StoreCapitalVirtualAccountService;
import com.groupbuying.store.service.StoreMainInfoService;
import com.groupbuying.store.utils.*;
import com.groupbuying.store.utils.apiresult.ApiResult;
import com.groupbuying.store.utils.apiresult.ApiResultCode;
import com.groupbuying.store.utils.apiresult.JsonUtils;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class StoreCapitalVirtualAccountDetailServiceImpl implements StoreCapitalVirtualAccountDetailService {
    private static Logger logger = LoggerFactory.getLogger(StoreCapitalVirtualAccountDetailServiceImpl.class);

    @Autowired
    private StoreCapitalVirtualAccountDetailDao storeCapitalVirtualAccountDetailDao;
    @Autowired
    private StoreMainInfoService storeMainInfoService;
    @Autowired
    private SysconfigFeign sysconfigFeign;
    @Autowired
    @Lazy
    private StoreCapitalVirtualAccountService storeCapitalVirtualAccountService;

    @Override
    public StoreCapitalVirtualAccountDetailDO get(String uuid) {
        return storeCapitalVirtualAccountDetailDao.get(uuid);
    }

    @Override
    public List<StoreCapitalVirtualAccountDetailDO> list(Map<String, Object> map) {
        return storeCapitalVirtualAccountDetailDao.list(map);
    }

    @Override
    public int count(Map<String, Object> map) {
        return storeCapitalVirtualAccountDetailDao.count(map);
    }

    @Override
    public int save(StoreCapitalVirtualAccountDetailDO storeCapitalVirtualAccountDetail) {
        return storeCapitalVirtualAccountDetailDao.save(storeCapitalVirtualAccountDetail);
    }

    @Override
    public int update(StoreCapitalVirtualAccountDetailDO storeCapitalVirtualAccountDetail) {
        return storeCapitalVirtualAccountDetailDao.update(storeCapitalVirtualAccountDetail);
    }

    @Override
    public int remove(String uuid) {
        return storeCapitalVirtualAccountDetailDao.remove(uuid);
    }

    @Override
    public int batchRemove(String[] uuids) {
        return storeCapitalVirtualAccountDetailDao.batchRemove(uuids);
    }

    @Override
    public void createStoreAccountLog(String storeUuid, String storeNo, String businessType, String inOrOut, BigDecimal operAmount, BigDecimal balance, BigDecimal freezeBalance, String billNo, String description, String oper, BigDecimal cashAmount, BigDecimal balanceAmount, BigDecimal integralAmount, BigDecimal operCashAmount, BigDecimal operBalanceAmount, BigDecimal operIntegralAmount) {
        StoreCapitalVirtualAccountDetailDO mdetail = new StoreCapitalVirtualAccountDetailDO();
        mdetail.setDelflag(CommonConstants.COMMON_FLAG_UNDEL);
        mdetail.setVersion(0);
        mdetail.setUuid(sysconfigFeign.getUuidByLeaf() + String.valueOf((int) ((Math.random() * 9 + 1) * 1000)));
        mdetail.setStoreuuid(storeUuid);
        mdetail.setStoreno(storeNo);
        mdetail.setBusinesstype(businessType);
        mdetail.setInorout(inOrOut);
        mdetail.setOperamount(operAmount);
        mdetail.setBalance(balance);
        mdetail.setFreezeBalance(freezeBalance);
        mdetail.setBillno(billNo);
        mdetail.setOper(oper);
        mdetail.setCreateoper(oper);
        mdetail.setCreateopetime(DateFormatHelper.getNowTimeStr("yyyy-MM-dd HH:mm:ss SSS"));
        StoreMainInfoDO storeMain = storeMainInfoService.get(storeUuid);
        mdetail.setStationuuid(storeMain != null ? storeMain.getStationuuid() : null);
        mdetail.setDescription(description);
        mdetail.setBalanceAmount(balanceAmount);
        mdetail.setIntegralAmount(integralAmount);
        mdetail.setCashAmount(cashAmount);
        mdetail.setOperBalanceAmount(operBalanceAmount);
        mdetail.setOperCashAmount(operCashAmount);
        mdetail.setOperIntegralAmount(operIntegralAmount);
        this.save(mdetail);
    }

    @Override
    public void createStoreAccountLog(String storeUuid, String storeNo, String businessType, String inOrOut, BigDecimal operAmount, BigDecimal balance, BigDecimal freezeBalance, String billNo, String description, String oper, String timeStamp, BigDecimal cashAmount, BigDecimal balanceAmount, BigDecimal integralAmount, BigDecimal operCashAmount, BigDecimal operBalanceAmount, BigDecimal operIntegralAmount) {
        StoreCapitalVirtualAccountDetailDO mdetail = new StoreCapitalVirtualAccountDetailDO();
        mdetail.setDelflag(CommonConstants.COMMON_FLAG_UNDEL);
        mdetail.setVersion(0);
        mdetail.setUuid(sysconfigFeign.getUuidByLeaf());
        mdetail.setStoreuuid(storeUuid);
        mdetail.setStoreno(storeNo);
        mdetail.setBusinesstype(businessType);
        mdetail.setInorout(inOrOut);
        mdetail.setOperamount(operAmount);
        mdetail.setBalance(balance);
        mdetail.setFreezeBalance(freezeBalance);
        mdetail.setBillno(billNo);
        mdetail.setOper(oper);
        mdetail.setCreateoper(oper);
        mdetail.setCreateopetime(timeStamp);
        mdetail.setOpetime(timeStamp);
        mdetail.setDescription(description);
        mdetail.setBalanceAmount(balanceAmount);
        mdetail.setIntegralAmount(integralAmount);
        mdetail.setCashAmount(cashAmount);
        mdetail.setOperBalanceAmount(operBalanceAmount);
        mdetail.setOperCashAmount(operCashAmount);
        mdetail.setOperIntegralAmount(operIntegralAmount);
        this.save(mdetail);
    }

    @Override
    public R getListByPage(Map<String, Object> params) {
        params.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        params.put("providerId", FilterContextHandler.getName());
        params.put("sort", "createTime");
        params.put("order", "desc");
        Query query = new Query(params);
        List<StoreCapitalVirtualAccountDetailDto> list = storeCapitalVirtualAccountDetailDao.getListByPage(query);
        for (StoreCapitalVirtualAccountDetailDto dto : list) {
            switch (dto.getBusinessType()) {
                case StoreVirtualOperConstants.PREFERENTIAL_ORDER_REFUND: {
                    dto.setBusinessType("优惠买单订单退款");
                }
                break;
                case StoreVirtualOperConstants.PREFERENTIAL_ORDER_SETTLE: {
                    dto.setBusinessType("优惠买单订单分账");
                }
                break;
                case StoreVirtualOperConstants.ORDER_WITHDRAW: {
                    dto.setBusinessType("商家提现");
                }
                break;
                case StoreVirtualOperConstants.OPTIMAL_STORE_ORDER_REFUND:{
                    dto.setBusinessType("够样优店订单退款");
                }
                break;
                case StoreVirtualOperConstants.OPTIMAL_STORE_ORDER_SETTLE:{
                    dto.setBusinessType("够样优店订单分账");
                }
                break;
            }
        }

        params.remove("limit");
        params.remove("page");
        query = new Query(params);
        List<StoreCapitalVirtualAccountDetailDto> totalList = storeCapitalVirtualAccountDetailDao.getListByPage(query);
        PageUtils pageUtil = new PageUtils(list, totalList.size());
        return R.ok().put("page", pageUtil);
    }


    @Override
    public PageUtils getFinancialPwdList(Map<String, Object> params) {
        params.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        params.put("providerId", FilterContextHandler.getName());
        Query query = new Query(params);
        List<Map<String,Object>> list = storeCapitalVirtualAccountDetailDao.getFinancialPwdList(query);
        int count = storeCapitalVirtualAccountDetailDao.countFinancialPwd(params);
        PageUtils pageUtil = new PageUtils(list, count);
        return pageUtil;
    }

    @Override
    public List<StoreCapitalVirtualAccountDetailDO> queryListByTime(String startTime, String endTime, String storeUuid) {

        Map<String, Object> params = new HashMap<>();
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("storeUuid", storeUuid);
        return storeCapitalVirtualAccountDetailDao.queryListByTime(params);
    }

    @Override
    public ApiResult changePwd(Map<String,Object> params){
        logger.error("StoreCapitalVirtualAccountDetailServiceImpl-->changePwd params:::"+JsonUtils.objectToJson(params));
        boolean checkFlag =  AccountCheckPwdUtils.checkParams(params);
        if(!checkFlag){
            logger.error("StoreCapitalVirtualAccountDetailServiceImpl-->changePwd fail 参数为空");
            return ApiResult.paramIsNull();
        }
        String uuid = (String) params.get("uuid");
        String newPwd = (String) params.get("newPwd");
        newPwd = MD5Utils.encrypt(newPwd);
        //参数校验，对比输入的旧密码，新密码与确认新密码是否一致等
        ApiResult compareResult = comparePwd(params);
        if(!ApiResultCode.SUCCESS.code().equals(compareResult.getCode())){
            logger.error("StoreCapitalVirtualAccountDetailServiceImpl-->changePwd "+uuid+" fail 参数校验失败");
            return compareResult;
        }
        //修改密码
        StoreCapitalVirtualAccountDO StoreCapitalVirtualAccountDO= new StoreCapitalVirtualAccountDO();
        StoreCapitalVirtualAccountDO.setUuid(uuid);
        StoreCapitalVirtualAccountDO.setVirtualpasswd(newPwd);
        int count = storeCapitalVirtualAccountService.update(StoreCapitalVirtualAccountDO);
        if(count <= 0){
            logger.error("StoreCapitalVirtualAccountDetailServiceImpl-->changePwd "+uuid+" fail:修改密码失败 count:"+count);
            return ApiResult.failure(ApiResultCode.FAILURE.code(),"修改密码失败");
        }
        return ApiResult.success();
    }

    private ApiResult comparePwd(Map<String,Object> params){
        logger.error("StoreCapitalVirtualAccountDetailServiceImpl-->comparePwd params:::"+JsonUtils.objectToJson(params));
        String uuid = (String) params.get("uuid");
        String oldPwd = (String) params.get("oldPwd");
        oldPwd = MD5Utils.encrypt(oldPwd);
        String newPwd = (String) params.get("newPwd");
        String notarizePwd = (String) params.get("notarizePwd");
        if(!newPwd.equals(notarizePwd)){
            logger.error("StoreCapitalVirtualAccountDetailServiceImpl-->comparePwd "+uuid+" fail:新密码与确认新密码不符");
            return ApiResult.failure(ApiResultCode.FAILURE.code(),"新密码与确认新密码不符");
        }
        Map virtualAccountParams =new HashMap();
        virtualAccountParams.put("uuid",uuid);
        logger.error("StoreCapitalVirtualAccountDetailServiceImpl-->comparePwd virtualAccountPassword params:::"+uuid);
        Map virtualAccountResult= storeCapitalVirtualAccountService.virtualAccountPassword(virtualAccountParams);
        logger.error("StoreCapitalVirtualAccountDetailServiceImpl-->comparePwd virtualAccountPassword "+uuid+" result:::"+JsonUtils.objectToJson(virtualAccountResult));
        if(MapUtils.isEmpty(virtualAccountResult)){
            logger.error("StoreCapitalVirtualAccountDetailServiceImpl-->comparePwd "+uuid+" fail:获取商户信息失败");
            return ApiResult.failure(ApiResultCode.FAILURE.code(),"获取商户信息失败");
        }
        String virtualPasswd = (String) virtualAccountResult.get("virtualPasswd");
        if(!virtualPasswd.equals(oldPwd)){
            logger.error("StoreCapitalVirtualAccountDetailServiceImpl-->comparePwd "+uuid+" fail:旧密码输入错误");
            return ApiResult.failure(ApiResultCode.FAILURE.code(),"旧密码输入错误");
        }
        return ApiResult.success();
    }

}
